package cn.iocoder.yudao.module.system.service.a_article;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.system.config.a_gaojian.CkmConfig;
import cn.iocoder.yudao.module.system.config.a_gaojian.ConnectionConfig;
import cn.iocoder.yudao.module.system.controller.admin.a_article.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.a_article.ArticleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.a_article.ArticleDOReq;
import cn.iocoder.yudao.module.system.dal.dataobject.a_article.ArticleLogDO;
import cn.iocoder.yudao.module.system.dal.dataobject.a_article.ArticleTempDO;
import cn.iocoder.yudao.module.system.dal.mysql.a_article.ArticleLogMapper;
import cn.iocoder.yudao.module.system.dal.mysql.a_article.ArticleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.a_article.ArticleTempMapper;
import cn.iocoder.yudao.module.system.service.a_articleLog.ArticleLogService;
import cn.iocoder.yudao.module.system.service.hybase.HyBaseService;
import cn.iocoder.yudao.module.system.util.a_gaojian.*;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.trs.hybase.client.*;
import com.trs.hybase.client.params.OperationParams;
import com.trs.hybase.client.params.SearchParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lxj
 */
@Service
@Validated
@Slf4j
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleLogService articleLogService;

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private ArticleTempMapper articleTempMapper;

    @Resource
    private ArticleLogMapper articleLogMapper;

    @Resource
    private CkmConfig ckmConfig;

    @Resource
    private HyBaseService hyBaseService;

    @Resource
    JdbcTemplate jdbcTemplate;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${fileData.coverPath}")
    private String coverPath;

    /**
     * 上传文稿插图文件存储在本地的根路径
     */
    @Value("${fileData.insetPath}")
    private String insetPath;

    /**
     * 删除文件存储在本地的根路径
     */
    @Value("${fileData.delPath}")
    private String delPath;

    /**
     * 文稿表名
     */
    @Value("${hybase.dbname.article}")
    private String dbName;

    /**
     * 文稿表名
     */
    @Value("${hybase.dbname.articleTemp}")
    private String articleTemp;


    private ArticleReqVO upload(ArticleReqVO articleReqVO) {
        String address;
        try {
            address = ImageUtils.upload(coverPath, articleReqVO.getCoverFile());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        //这里可以将需要的字段保存至数据库
        articleReqVO.setCoverUrl(coverPath + address);

        return articleReqVO;
    }

    @Override
    public String insertHybaseByArticle(ArticleReqVO createReqVO) {
//        CkmConfig ckmConfig = new CkmConfig();
//        if (createReqVO.getCoverFile() != null) {
//            createReqVO = upload(createReqVO);
//        }
//        //创建与服务器的连接实例
//        TRSConnection conn = ConnectionConfig.getTRSConnection();
//        //创建记录对象
//        List<TRSInputRecord> recordList = new ArrayList<>();
//        TRSInputRecord record = new TRSInputRecord();
//        Long userId = WebFrameworkUtils.getLoginUserId();
//        TRSReport trsReport = new TRSReport();
//        String uuid = IdUtil.fastSimpleUUID();
//        //添加字段
//        try {
//            record.addColumn("id", uuid);
//            record.addColumn("title", createReqVO.getTitle());
//            record.addColumn("content", createReqVO.getContent());
//            record.addColumn("category", createReqVO.getCategory());
//            record.addColumn("version", 1);
//            record.addColumn("create_user_id", userId);
//            record.addColumn("create_user_name", createReqVO.getCreateUserName());
//            String nowTime = DateUtils.formatDateToStr(new Date());
//            record.addColumn("create_time", nowTime);
//            record.addColumn("last_modification_time", nowTime);
//            record.addColumn("deleted", 0);
//            record.addColumn("coverUrl", createReqVO.getCoverUrl());
//            record.addColumn("review_status", 0);
//            recordList.add(record);
//            //执行插入记录（暂时在内存中）
//            conn.executeInsert(dbName, recordList, new OperationParams(), trsReport);
//            ArticleReqVO articleLog = get(uuid);
//            articleLogService.insertArticleLog(conn, articleLog);
//
//            if (trsReport.getInsertedNum() > 0) {
//                try {
//                    System.out.println("getContent ======> " + createReqVO.getContent().replaceAll("<[^>]+>", ""));
//                    System.out.println("getTitle ======> " + createReqVO.getTitle());
//                    // 将稿件正文存储到查重库
//                    ckmConfig.update(createReqVO.getContent().replaceAll("<[^>]+>", ""),createReqVO.getTitle());
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                }
//                return uuid;
//            }
//        } catch (TRSException e) {
//            e.printStackTrace();
//        }
        return "";
    }

    @Override
    public PageResult<ArticlePageReqVO> getPage(ArticlePageReqVO pageReqVO) {
        PageResult<ArticlePageReqVO> pageResult = new PageResult<>();
        List<ArticlePageReqVO> articlePageReqVOList = new ArrayList<>();
        //创建与服务器的连接实例
        TRSConnection conn = ConnectionConfig.getTRSConnection();
        SearchParams param = new SearchParams();
        //设置结果排序方式为创建时间排序
        param.setSortMethod("-create_time");
        //设置返回结果字段
        param.setReadColumns("id;title;content;category;create_user_id;create_user_name;create_time;last_modification_time;version;coverUrl;review_status;is_share;is_push;");
        TRSResultSet resultSet;
        Long userId = WebFrameworkUtils.getLoginUserId();

        String whereStr =  (StringUtils.isNotBlank(pageReqVO.getIsShare())) ? "deleted:0 AND is_share:1":"deleted:0 AND create_user_id:" + userId;
        if (StringUtils.isNotBlank(pageReqVO.getTitle())) {
            whereStr += " AND title:" + pageReqVO.getTitle();
        }
        if (StringUtils.isNotBlank(pageReqVO.getContent())) {
            whereStr += " AND content:" + pageReqVO.getContent();
        }
        if (StringUtils.isNotBlank(pageReqVO.getCategory())) {
            whereStr += " AND category:" + pageReqVO.getCategory();
        }

        try {
            //在"pictures"数据库里检索
            resultSet = conn.executeSelect(dbName, whereStr, ((pageReqVO.getPageNo() - 1) * pageReqVO.getPageSize()), pageReqVO.getPageSize(), param);
            if (resultSet != null) {
                for (int i = 0; i < resultSet.size(); i++) {
                    resultSet.moveNext();
                    TRSRecord re = resultSet.get();
                    ArticlePageReqVO articlePageReqVO = new ArticlePageReqVO();
                    articlePageReqVO.setId(re.getString("id"));
                    articlePageReqVO.setTitle(re.getString("title"));
                    articlePageReqVO.setContent(re.getString("content"));
                    articlePageReqVO.setCategory(re.getString("category"));
                    articlePageReqVO.setCreateUserId(re.getString("create_user_id"));
                    articlePageReqVO.setCreateUserName(re.getString("create_user_name"));
                    articlePageReqVO.setVersion(re.getInt("version"));
                    articlePageReqVO.setCreateTime(re.getString("create_time"));
                    articlePageReqVO.setLastModificationTime(re.getString("last_modification_time"));
                    articlePageReqVO.setCoverUrl(re.getString("coverUrl"));
                    articlePageReqVO.setReviewStatus(re.getInt("review_status"));
                    articlePageReqVO.setIsShare(re.getString("is_share"));
                    articlePageReqVO.setIsPush(re.getString("is_push"));
                    articlePageReqVOList.add(articlePageReqVO);
                }

                pageResult.setTotal(resultSet.getNumFound());
                pageResult.setList(articlePageReqVOList);

            }
        } catch (TRSException e) {
            System.out.println("ErrorCode:" + e.getErrorCode());
            System.out.println("ErrorString:" + e.getErrorString());
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return pageResult;
    }

    @Override
    public Boolean updateReview(String id, Integer reviewStatus) {
        String sql = String.format("update gj_article set review_status = %s where id = %s", reviewStatus, id);
        int row = jdbcTemplate.update(sql);

        // 异步同步数据到海贝
        CompletableFuture.runAsync(() -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("review_status", reviewStatus);
            hyBaseService.updateHybaseById(dbName, Long.valueOf(id), map);
        });
        return row > 0;
    }



    @Override
    public Boolean delete(String ids, String urls) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<String> urlList = new ArrayList<>();
        if (StringUtils.isNotBlank(urls)) {
            urlList = Arrays.asList(urls.split(","));
        }
        //创建与服务器的连接实例
        TRSConnection conn = ConnectionConfig.getTRSConnection();
        List<TRSInputRecord> newValues = new ArrayList<>();
        OperationParams params = new OperationParams();
        TRSReport trsReport = new TRSReport();
        params.setProperty("unique.column.search", "true");
        params.setProperty("unique.column", "id");
        try {
            for (int i = 0; i < idList.size(); i++) {
                TRSInputRecord record = new TRSInputRecord();
                record.addColumn("id", idList.get(i));
                record.addColumn("deleted", 1);
                if (StringUtils.isNotBlank(urls)) {
                    record.addColumn("coverUrl", FileUtils.moveFile(delPath, urlList.get(i)));
                }
                newValues.add(record);
            }
            conn.executeUpdate(dbName, newValues, params, trsReport);
        } catch (TRSException e) {
            e.printStackTrace();
        }
        return trsReport.getUpdatedNum() > 0;
       /* //创建与服务器的连接实例
        TRSConnection conn = new TRSConnection(url, username, password, new ConnectParams());
        try {
            conn.executeDelete(dbName, ids.split(","));
        } catch (TRSException e) {
            e.printStackTrace();
        }*/
    }

    @Override
    public ArticleDO get(String id) {
        return articleMapper.selectById(id);
    }

    @Override
    public Boolean updateHybaseByArticle(ArticleReqVO updateReqVO) {
//        if (updateReqVO.getCoverFile() != null) {
//            updateReqVO = upload(updateReqVO);
//        }
//        updateReqVO.setVersion(updateReqVO.getVersion() + 1);
//        updateReqVO.setLastModificationTime(DateUtils.formatDateToStr(new Date()));
//        //创建与服务器的连接实例
//        TRSConnection conn = ConnectionConfig.getTRSConnection();
//        List<TRSInputRecord> newValues = new ArrayList<>();
//        OperationParams params = new OperationParams();
//        TRSReport trsReport = new TRSReport();
//        params.setProperty("unique.column.search", "true");
//        params.setProperty("unique.column", "id");
//        try {
//            TRSInputRecord record = new TRSInputRecord();
//            record.addColumn("id", updateReqVO.getId());
//            record.addColumn("title", updateReqVO.getTitle());
//            record.addColumn("content", updateReqVO.getContent());
//            record.addColumn("version", updateReqVO.getVersion());
//            record.addColumn("category", updateReqVO.getCategory());
//            record.addColumn("last_modification_time", updateReqVO.getLastModificationTime());
//            record.addColumn("create_user_id", updateReqVO.getCreateUserId());
//            record.addColumn("create_user_name", updateReqVO.getCreateUserName());
//            if (updateReqVO.getCoverFile() != null) {
//                record.addColumn("coverUrl", updateReqVO.getCoverUrl());
//            }
//            newValues.add(record);
//
//            ArticleReqVO articleLog = get(updateReqVO.getId());
//            if (!articleLogService.findExistByRelevanceId(conn, updateReqVO.getId())) {
//                articleLogService.insertArticleLog(conn, articleLog);
//            }
//
//            conn.executeUpdate(dbName, newValues, params, trsReport);
//
//            try {
//                ArticleReqVO newArticleReqVO = new ArticleReqVO();
//                Map<String, Object> updateReqVOMap = ManuscriptLogUtils.objectToMap(updateReqVO);
//                Map<String, Object> articleLogMap = ManuscriptLogUtils.objectToMap(articleLog);
//                updateReqVOMap.remove("coverFile");
//                articleLogMap.remove("coverFile");
//                Map<String, Object> newMap = ManuscriptLogUtils.mapCompare(updateReqVOMap, articleLogMap);
//                if (!newMap.isEmpty()) {
//                    ObjectMapper objectMapper = new ObjectMapper();
//                    newArticleReqVO = objectMapper.convertValue(newMap, ArticleReqVO.class);
//                }
//                articleLogService.insertArticleLog(conn, newArticleReqVO);
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//                log.error("图片修改日志添加失败", updateReqVO, e);
//            }
//
//
//        } catch (TRSException e) {
//            e.printStackTrace();
//        }
        return true;
    }

    @Override
    public String uploadInset(MultipartFile insetImage) {
        String address;
        try {
            // 通过MultipartFile得到InputStream，从而得到BufferedImage
            address = ImageUtils.upload(insetPath, insetImage);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        //总路径
        String url = address;
        //这里可以将需要的字段保存至数据库
        return insetPath + url;
    }

    @Override
    public Boolean deleteInset(String insetUrls) {
        List<String> delUrls = Arrays.asList(insetUrls.split(","));
        //删除文件
        return FileUtils.deleteFileByFileNameAndPath(delUrls);
    }

    @Override
    public Map<String, Object> duplicate(ArticleDuplicateReqVO articleDuplicateReqVO) {
        CkmConfig ckmConfig = new CkmConfig();
        List<String> filePathList;
        Map<String, Integer> insertMap = new HashMap<>();
        Map<String, Object> resultMap = new HashMap<>();
        String content = articleDuplicateReqVO.getContent();
        //内容查询
        try {
            Pattern pattern = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);

            Matcher matcher = pattern.matcher(content);
            content = matcher.replaceAll("");
            String contentDuplicateNum = ckmConfig.retrieve(content);
            if (StringUtils.isNotBlank(articleDuplicateReqVO.getInsertUrls())) {
                filePathList = Arrays.asList(articleDuplicateReqVO.getInsertUrls().split(","));
                for (String filePath : filePathList) {
                    insertMap.put(filePath, ImageUtils.insetDuplicate(filePath, insetPath));
                }
            }
            resultMap.put("insert", insertMap);
            resultMap.put("content", contentDuplicateNum);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultMap;
    }


    @Override
    public long insertArticleByDay() {
        //创建与服务器的连接实例
        TRSConnection conn = ConnectionConfig.getTRSConnection();
        SearchParams param = new SearchParams();
        TRSResultSet resultSet;

        String whereStr = "deleted:0 AND create_user_id:" + WebFrameworkUtils.getLoginUserId() + " AND create_time:[" + DateUtils.formatYYYYMMDDToStr(DateUtils.getDayStart(new Date())) + " TO " + DateUtils.formatYYYYMMDDToStr(DateUtils.getDayStart(new Date())) + "]";
        try {
            //在"pictures"数据库里检索
            resultSet = conn.executeSelect(dbName, whereStr, 0, 10000, param);
            if (resultSet != null) {
                return resultSet.getNumFound();
            }
        } catch (TRSException e) {
            System.out.println("ErrorCode:" + e.getErrorCode());
            System.out.println("ErrorString:" + e.getErrorString());
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return 0;
    }

    @Override
    public Boolean insertArticleTemp(ArticleReqVO createReqVO) {
        if (createReqVO.getCoverFile() != null) {
            createReqVO = upload(createReqVO);
        }
        ArticleTempDO articleTempDO = new ArticleTempDO();
        BeanUtils.copyProperties(createReqVO, articleTempDO);
        articleTempDO.setRelevanceId(Long.valueOf(createReqVO.getId()));
        int insert = articleTempMapper.insert(articleTempDO);
        log.info("新增文稿暂存：{}", insert);
        return insert > 0;
    }

    @Override
    public Boolean deleteArticleTemp(Long[] ids) {
        for (Long id : ids) {
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("relevance_id", id);
            return articleTempMapper.delete(wrapper) < 1;
        }
        return false;
    }

    @Override
    public ArticleTempDO getArticleTemp(String relevanceId) {
        List<ArticleTempDO> tempDOList = articleTempMapper.selectList("relevance_id", relevanceId);
        tempDOList.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
        return tempDOList.isEmpty() ? null : tempDOList.get(0);
    }

    @Override
    public PageResult<AticleRLPicturesPageReqVO> getRLPicturesPage(AticleRLPicturesPageReqVO pageReqVO) {
        PageResult<AticleRLPicturesPageReqVO> pageResult = new PageResult<>();
        List<AticleRLPicturesPageReqVO> aticleRLPicturesPageReqVOList = new ArrayList<>();
        //创建与服务器的连接实例
        TRSConnection conn = ConnectionConfig.getTRSConnection();
        SearchParams param = new SearchParams();
        //设置结果排序方式为创建时间排序
        param.setSortMethod("-createTime");
        //设置返回结果字段
        param.setReadColumns("id;releaseTime;url;name");
        TRSResultSet resultSet;
        Long userId = WebFrameworkUtils.getLoginUserId();
        String whereStr = "*:*";

        try {
            //在"pictures"数据库里检索
            resultSet = conn.executeSelect("rl_picture", whereStr, ((pageReqVO.getPageNo() - 1) * pageReqVO.getPageSize()), pageReqVO.getPageSize(), param);
            if (resultSet != null) {
                for (int i = 0; i < resultSet.size(); i++) {
                    resultSet.moveNext();
                    TRSRecord re = resultSet.get();
                    AticleRLPicturesPageReqVO aticleRLPicturesPageReqVO = new AticleRLPicturesPageReqVO();
                    aticleRLPicturesPageReqVO.setId(re.getString("id"));
                    aticleRLPicturesPageReqVO.setName(re.getString("name"));
                    aticleRLPicturesPageReqVO.setReleaseTime(re.getString("releaseTime"));
                    aticleRLPicturesPageReqVO.setUrl(re.getString("url"));
                    aticleRLPicturesPageReqVOList.add(aticleRLPicturesPageReqVO);
                }
                pageResult.setTotal(resultSet.getNumFound());
                pageResult.setList(aticleRLPicturesPageReqVOList);

            }
        } catch (TRSException e) {
            System.out.println("ErrorCode:" + e.getErrorCode());
            System.out.println("ErrorString:" + e.getErrorString());
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return pageResult;
    }

    @Override
    public PageResult<AticleRLVideoPageReqVO> getRLVideoPage(AticleRLVideoPageReqVO pageReqVO){
        PageResult<AticleRLVideoPageReqVO> pageResult = new PageResult<>();
        List<AticleRLVideoPageReqVO> aticleRLVideoPageReqVOList = new ArrayList<>();
        //创建与服务器的连接实例
        TRSConnection conn = ConnectionConfig.getTRSConnection();
        SearchParams param = new SearchParams();
        //设置结果排序方式为创建时间排序
        param.setSortMethod("-createTime");
        //设置返回结果字段
        param.setReadColumns("id;releaseTime;url;name;thumb");
        TRSResultSet resultSet;
        Long userId = WebFrameworkUtils.getLoginUserId();
        String whereStr = "*:*";

        try {
            //在"pictures"数据库里检索
            resultSet = conn.executeSelect("rl_video", whereStr, ((pageReqVO.getPageNo() - 1) * pageReqVO.getPageSize()), pageReqVO.getPageSize(), param);
            if (resultSet != null) {
                for (int i = 0; i < resultSet.size(); i++) {
                    resultSet.moveNext();
                    TRSRecord re = resultSet.get();
                    AticleRLVideoPageReqVO aticleRLVideoPageReqVO = new AticleRLVideoPageReqVO();
                    aticleRLVideoPageReqVO.setId(re.getString("id"));
                    aticleRLVideoPageReqVO.setName(re.getString("name"));
                    aticleRLVideoPageReqVO.setReleaseTime(re.getString("releaseTime"));
                    aticleRLVideoPageReqVO.setUrl(re.getString("url"));
                    aticleRLVideoPageReqVO.setThumb(re.getString("thumb"));
                    aticleRLVideoPageReqVOList.add(aticleRLVideoPageReqVO);
                }
                pageResult.setTotal(resultSet.getNumFound());
                pageResult.setList(aticleRLVideoPageReqVOList);

            }
        } catch (TRSException e) {
            System.out.println("ErrorCode:" + e.getErrorCode());
            System.out.println("ErrorString:" + e.getErrorString());
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return pageResult;
    }

    @Override
    public Boolean updateShare(String id , String shareStatus) {
        String sql = String.format("update gj_article set is_share = %s where id = %s", shareStatus, id);
        int row = jdbcTemplate.update(sql);

        // 异步同步数据到海贝
        CompletableFuture.runAsync(() -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("is_share", shareStatus);
            hyBaseService.updateHybaseById(dbName, Long.valueOf(id), map);
        });
        return row > 0;
    }

    @Override
    public Boolean updatePush(String id, String pushStatus) {
        ArticleDO articleDO = get(id);
        articleDO.setIsPush(pushStatus);
        int update = articleMapper.updateById(articleDO);

        // 异步同步数据到海贝
        CompletableFuture.runAsync(() -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("is_push", pushStatus);
            hyBaseService.updateHybaseById(dbName, Long.valueOf(id), map);
        });
        return update > 0;
    }

    @Override
    public Boolean creatModel() {
        CkmConfig ckmConfig = new CkmConfig();
        Boolean result = false;
        try {
            result = "1".equals(ckmConfig.create()) ? true : false;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public Long save(ArticleDOReq articleDOReq) {
        try {
            // 上传封面并设置封面 URL
            String coverUrl = uploadCover(articleDOReq.getCoverFile());
            if (coverUrl != null) articleDOReq.setCoverUrl(coverUrl);

            // 保存文章并记录日志
            ArticleDO articleDO = new ArticleDO();
            BeanUtils.copyProperties(articleDOReq, articleDO);
            ArticleLogDO articleLogDO = createArticleLog(articleDO);

            Boolean isSaved = articleMapper.save(articleDO);
            log.info("保存文稿：{}", isSaved);

            articleLogDO.setRelevanceId(articleDO.getId());
            Boolean saveLog = articleLogMapper.save(articleLogDO);
            log.info("保存文稿日志：{}", saveLog);

            // 更新内容
            Boolean update = ckmConfig.update(cleanContent(articleDO.getContent()), articleDO.getTitle());
            log.info("修改文稿ckm内容：{}", update);

            return articleDO.getId();
        } catch (IOException e) {
            log.info("文稿保存失败！:{}", e.getMessage());
            throw new ServiceException(501, "文稿保存失败，请联系管理员!");
        }
    }

    private String uploadCover(MultipartFile coverFile) throws IOException {
        if (coverFile != null) {
            return coverPath + ImageUtils.upload(coverPath, coverFile);
        }
        return null;
    }

    private ArticleLogDO createArticleLog(ArticleDO articleDO) {
        ArticleLogDO articleLogDO = new ArticleLogDO();
        BeanUtils.copyProperties(articleDO, articleLogDO);
        articleLogDO.setId(null);
        articleLogDO.setRelevanceId(articleDO.getId());
        return articleLogDO;
    }

    private String cleanContent(String content) {
        return content.replaceAll("<[^>]+>", "");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(Long[] ids) {
        for (Long id : ids) {
            int row = articleMapper.deleteById(id);
            log.info("删除文稿：{}", row);
            int rowLog = articleLogMapper.deleteById(id);
            log.info("删除文稿日志：{}", rowLog);
            int rowTemp = articleTempMapper.deleteById(id);
            log.info("删除文稿模板：{}", rowTemp);
            //同步删除海贝
            CompletableFuture future = CompletableFuture.runAsync(() -> {
                hyBaseService.executeDeleteQuery(dbName, id);
            });
        }
        return true;
    }

    @Override
    public PageResult<ArticleDO> selectPage(ArticlePageReqVO pageVO) {
        return articleMapper.page(pageVO);
    }

}
